import 'dart:async';

import 'package:flutter_blue/flutter_blue.dart';
import 'dart:io';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:magic_car/common/global.dart';
import 'package:magic_car/user/agenterror.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:magic_car/util/colors.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'package:toast/toast.dart';
import 'package:magic_car/main.dart';
//import 'package:amap_location/amap_location.dart';
import 'package:permission_handler/permission_handler.dart';

//import 'package:flutter/bluetooth/bluetooth.dart';
class BluePage extends StatefulWidget {
  BluePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<BluePage> {
  List formList = [];
  List<BluetoothDevice> devices = [];
  bool startscan = false;
  FlutterBlue flutterBlue = FlutterBlue.instance;
  BluetoothDevice device;

  BluetoothCharacteristic cread;
  BluetoothCharacteristic cwrite;

  String sendCode = "ATZ";
  initState() {
    super.initState();

    startLcoations();
    // getLocationInfo();
  }

  Widget buildcontent() {
    List<Widget> tiles = [];
    Widget content;
    if (formList.length > 0) {
      for (var i = 0; i < formList.length; i++) {
        var item = formList[i];
        tiles.add(Padding(
            padding: new EdgeInsets.fromLTRB(15, 15, 15, 0),
            child: Container(
              width: double.infinity - 20,
              decoration: new BoxDecoration(
                color: Colors.white,
              ),
              child: new GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    print('1212');
                    device = devices[i];

                    startconnetc(i);
                  },
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Padding(
                        padding: new EdgeInsets.fromLTRB(20, 15, 20, 10),
                        child: Column(
                          children: <Widget>[
                            Text(item["name"]),
                            Text(item['value'])
                          ],
                        ),
                      ),
                    ],
                  )),
            )));
      }
    }
    content = new Column(
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }

  startLcoations() async {
    print('开始定位');

if(await Permission.location.request().isGranted) {
      // 干你该干的事
    }
   
  }

  change() {
    Map<String, String> map = new Map();
    map['str'] = "ATZ";

    String api = HttpHelper.API_ChangeByte;

    HttpHelper.post(api, (data) async {
      if (data != null) {
        print(data);
        Toast.show(data["msg"], context);

        // pref.setStringList('userinfo', data["info"]);

      }
    }, params: map);
  }

  //发送数据
  writedata(str) async {
    List<int> b = Utf8Codec().encode(str + '\r');
    //print('写入值$b');
    print('写入值转换：$str');
    await cwrite.write(b);
    //cwrite.flush();
  }

  int num = 0;
  startconnetc(index) async {
    const timeout = const Duration(seconds: 5);
    flutterBlue.stopScan();
    await device.disconnect();
    await device.connect();

    setState(() {});

    List<BluetoothService> services = await device.discoverServices();
    services.forEach((service) async {
      // do something with service
      var characteristics = service.characteristics;
      for (BluetoothCharacteristic c in characteristics) {
        print('cuuid-------');
        print(c.uuid.toString());

        //List<int> b=Utf8Codec().encode('ATSP'+num.toString());
        //ATZ
        List<int> b = Utf8Codec().encode('ATZ\r\n');
        num = 0;
        // if(c.uuid.toString()==GattAttributes.BLE_SPP_SERVICE_READ){

        // }

        //00002a00-0000-1000-8000-00805f9b34fb
        //0000fff2-0000-1000-8000-00805f9b34fb
        if (c.uuid.toString() == "00002a01-0000-1000-8000-00805f9b34fb") {
          cwrite = c;
          writedata(sendCode);
        }
        //0000fff1-0000-1000-8000-00805f9b34fb
        //00002a01-0000-1000-8000-00805f9b34fb
        if (c.uuid.toString() == "00002a00-0000-1000-8000-00805f9b34fb") {
          Timer(timeout, () async {
            await c.setNotifyValue(true);
          });

          c.value.listen((value) async {
            var item = formList[index];

            if (value.length == 0) {
            } else {
              String recieve = Utf8Codec().decode(value).toString().trim();
              print('接收值$value');
              print('接收值转换结果$recieve');
              item['value'] = '发送指令$sendCode' + '接收值$recieve';

              if (recieve.contains("41")) {
                // if (recieve.contains('OK')) {
                print('协议走通，协议为$num');

                sendCode = '03';

                //  sendCode = "$sendCode";
                writedata(sendCode);
              }

              if (sendCode == "ATZ") {
                if (recieve[0] == "E") {
                  sendCode = "ATL0";
                  writedata(sendCode);
                } else {
                  writedata(sendCode);
                }
              } else if (sendCode == "ATL0") {
                if (recieve[0] == "A") {
                  sendCode = "ATE1";
                  writedata(sendCode);
                } else {
                  writedata(sendCode);
                }
              } else if (sendCode == "ATE1") {
                if (recieve[2] == "E") {
                  sendCode = "ATH0";
                  writedata(sendCode);
                } else {
                  writedata(sendCode);
                }
              } else if (sendCode == "ATH0") {
                if (recieve[2] == "H") {
                  sendCode = "ATSP0";
                  writedata(sendCode);
                } else {
                  writedata(sendCode);
                }
              } else if (sendCode == "ATSP" + num.toString()) {
                if (recieve.contains('OK') && recieve.contains('ATSP')) {
                  sendCode = "0100";
                  writedata(sendCode);
                } else {
                  // if (num < 9) {
                  //   num++;
                  // } else {
                  //   num = 0;
                  // }
                  // sendCode = "ATSP" + num.toString();
                  // writedata(sendCode);
                }
              } else if (sendCode == "0100") {
                if (recieve.contains("41")) {
                  // if (recieve.contains('OK')) {
                  print('协议走通，协议为$num');

                  sendCode = '03';

                  //  sendCode = "$sendCode";
                  writedata(sendCode);
                } else {
                  if (num < 9) {
                    num++;
                  } else {
                    num = 0;
                  }
                  sendCode = "ATSP" + num.toString();
                  writedata(sendCode);
                }
              } else if (sendCode == "0101") {
                print('------故障代码个数返回值-------$recieve');
              } else if (sendCode.contains('03')) {
                print('------故障代码返回值-------$recieve');
              } else if (sendCode == '04') {
                print('------清楚故障代码返回值-------$recieve');
              } else if (sendCode == '07') {
                print('------07故障代码返回值-------$recieve');
              } else if (sendCode == "01") {
                print('------故障代码返回值01-------$recieve');
              } else if (sendCode == "0120") {
                //pid20-40
                if (recieve.contains("41")) {
                  sendCode = "0140";
                  writedata(sendCode);
                } else {
                  // //继续查找40断的pid是否支持
                  // sendCode = "0140";
                  // writedata(sendCode);
                }
              } else if (sendCode == "0140") {
                if (recieve.contains("41")) {
                  sendCode = "0160";
                }
                writedata(sendCode);
              } else if (sendCode == "0160") {
                if (recieve.contains("41")) {
                  sendCode = "010D";
                }
                writedata(sendCode);
              } else if (sendCode == "010D") {
                print('010D 返回数据$recieve');
                if (recieve.contains("41")) {
                  sendCode = "03";
                }
                writedata(sendCode);
              }

              setState(() {
                formList = formList;
              });
            }
            // print('88888888888888888888888$value');
          });
        }
      }
    });
  }

//漆膜仪连接
  connect() async {
//     flutterBlue.connectedDevices.then((value) {
//             /// 逻辑
//             ///
//             print('已连接设备$value');
//  });
    //  Future<List<BluetoothDevice>> devices = flutterBlue.connectedDevices;

    // //  for(int i =0;i<devices.length;i++){

    // //  }
    //  print('连接的设备列表$devices');
    // SystemSetting.goto(SettingTarget.BLUETOOTH);
    // LoadingPage loadpage = new LoadingPage(context);
    // loadpage.show();
    //flutterBlue.startScan();

    flutterBlue.scan(scanMode: ScanMode.lowLatency).listen((scanresult) {
      print(scanresult.device);
      print('蓝牙名称' + scanresult.device.name);
      print('蓝牙名称12121' + scanresult.advertisementData.localName);

      String deveceName = scanresult.advertisementData.localName;
      String deviceId = scanresult.device.id.toString();
      if (startscan == false) {
        formList = [];
        devices = [];
      }
      var item = {'name': deviceId, 'value': ''};
      formList.add(item);
      devices.add(scanresult.device);
      setState(() {
        formList = formList;
        devices = devices;
      });
      if (deveceName.startsWith('OBD')) {
        flutterBlue.stopScan();
      }
      // if (deveceName.startsWith('OBD')) {
      //   // loadpage.close();
      //   Future.delayed(Duration(seconds: 0), () {});

      //   device = scanresult.device;

      //   flutterBlue.stopScan();
      // } else {
      //   //Toast.show('正在重新扫描设备', context);
      // }
    });
  }

  //}

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('蓝牙'),
        backgroundColor: Colors.white,
        elevation: 0,
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          //change();
          if (startscan == false) {
            connect();
            setState(() {
              startscan = true;
            });
          } else {
            flutterBlue.stopScan();
            setState(() {
              startscan = false;
            });
          }
        },
        child: Icon(
          Icons.add,
          color: Colors.white,
        ),
        backgroundColor: Colours.app_main,
      ),
      body: new ListView(
        children: <Widget>[buildcontent()],
      ),
    );
  }
}
